package com.itheima.sh.autoconfigure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.Jedis;

/**
 * @Description:
 * @Version: V1.0
 */
@Configuration(proxyBeanMethods = false)
// 条件
@ConditionalOnClass(Jedis.class)
//@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class HeimaRedisAutoConfiguration {

    private RedisProperties redisProperties;

    public HeimaRedisAutoConfiguration(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    @Bean
    public RedisSerializer<Object> redisKeySerializer() {
        return new Jackson2JsonRedisSerializer<Object>(Object.class);
    }

    @Bean
    public RedisSerializer<Object> redisValueSerializer() {
        return new Jackson2JsonRedisSerializer<Object>(Object.class);
    }

    /**
     * RedisTemplate配置
     */
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        JedisConnectionFactory factory = new JedisConnectionFactory();

        // 设置相关属性
        factory.setHostName(redisProperties.getHost());
        factory.setPort(redisProperties.getPort());
        factory.setDatabase(redisProperties.getDatabase());
        factory.setPassword(redisProperties.getPassword());
        factory.setTimeout((int) redisProperties.getTimeout().getSeconds());

        // 创建RedisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setDefaultSerializer(this.redisValueSerializer());
        redisTemplate.setKeySerializer(this.redisKeySerializer());
        redisTemplate.setHashKeySerializer(this.redisKeySerializer());
        redisTemplate.afterPropertiesSet();

        System.out.println("********* HeimaRedisAutoConfiguration redisTemplate is init ********* ");
        return redisTemplate;
    }
}
